const express = require('express')
const app = express()

var http=require('http').Server(app);
var io=require('socket.io')(http);

// mongoose
const mongoose = require('mongoose');
const config = require('./Config')
mongoose.Promise = global.Promise; //使用node promise
mongoose.connect(config.dbConfig.URL, { useNewUrlParser: true });
const db = mongoose.connection;
db.on('error', () => {
    console.log('数据库连接出错!');
});
db.once('open', () => {
    console.log('数据库连接成功！');
});



const bodyParser = require('body-parser')
const formatTime = require('./tool/formatTime')
const captcha = require('svg-captcha');


app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

let session = require('express-session')
const flash = require('connect-flash')
app.use(session({
  secret: 'keyboard cat',
  resave: false,
  saveUninitialized: true
}))
app.use(flash());
//公开public目录
app.use('/public', express.static('./public'))

//配置模板引擎
const template = require('art-template')
app.engine('html', require('express-art-template'))
template.defaults.imports.admin = function (value) { //管理員過濾器
  let level
  switch (value) {
    case 0:
      level = '超级管理员'
      break;
    case 1:
      level = '网站编辑'
      break;
    case 2:
      level = '作者'
      break;
    default:
      level = '游客'
  }
  return level
}
template.defaults.imports.fenlei = function (value) { //分类过滤器
    let arr = setTreeData(value)
    let tree =''
    let index =1
    goTree(arr)
    function goTree(arr) {
      index++
      if(arr.length>0){
        if(index%2){
          tree +=' <ul class="nav nav-third-level">'
        }else{
          tree +=' <ul class="nav nav-second-level">'
        }
        for(let i in arr){
          if(arr[i].children){
            tree +=`<li><a  class="J_menuItem" href="/admin/category-admin${arr[i].cateid}">${arr[i].name}<span class="fa arrow"></span></a>`;
            goTree(arr[i].children);
            tree +='</li>'
          }else{
            tree += `<li><a class="J_menuItem" href="/admin/category-admin${arr[i].cateid}">${arr[i].name}</a></li>` 
          }
        }
        tree +='</ul>'
      } 
    }
   
  function setTreeData(source){
    let cloneData = JSON.parse(JSON.stringify(source))      // 对源数据深度克隆
    return  cloneData.filter(father=>{                      // 循环所有项，并添加children属性
        let branchArr = cloneData.filter(child=> father.cateid == child.fatherId);   // 返回每一项的子级数组
        branchArr.length>0 ? father.children=branchArr : ''   //给父级添加一个children属性，并赋值
        return father.fatherId==0;      //返回第一层
    });
  }
  return tree
}
template.defaults.imports.timestamp= function(value){
  return formatTime(value)
  }
template.defaults.imports.timestamp1=function(value){
  var date = new Date(value);
  var y = date.getFullYear();
  var m = date.getMonth() + 1;
  m = m < 10 ? ('0' + m) : m;
  var d = date.getDate();
  d = d < 10 ? ('0' + d) : d;
  var h = date.getHours();
  h = h < 10 ? ('0' + h) : h;
  var minute = date.getMinutes();
  var second = date.getSeconds();
  minute = minute < 10 ? ('0' + minute) : minute;
  second = second < 10 ? ('0' + second) : second;
  return y + '-' + m + '-' + d + ' ' + h + ':' + minute + ':' + second;
} 
  

let adminRouter = require('./router/admin')
let arctileRouter = require('./router/acticle')
let cateRouter = require('./router/category')
let tagRouter = require('./router/tag')
let upload = require('./router/upload')
let blog = require('./router/blog')
let gbook = require('./router/gbook')
let comments = require('./router/comments')

app.use('/admin', adminRouter)
app.use('/admin', arctileRouter)
app.use('/admin', cateRouter)
app.use('/admin', tagRouter)
app.use('/admin', gbook)
app.use('/upload', upload)
app.use('/', blog)
app.use('/', gbook)
app.use('/', comments)
//获取验证码
app.get('/captcha',(req,res)=>{
  const cap = captcha.create();
  req.session.captcha = cap.text; // session 存储
  res.type('svg'); // 响应的类型
  res.send(cap.data);
});


app.use(function (req, res) {
  if (!res.headersSent) {
    res.status(404).render('404.html')
  }
})

app.use(function(err, req, res, next) {
  res.status(500);
  res.render('500.html')
});


/**
 *  socket.io开始
 * 
 */
var onlineUserCount=0; //客户端连接数量
var onlineUsers={}; //统计客户端登录用户
 
io.on('connection',function(socket){
    socket.emit('open');  //通知客户端已连接 
    //构造客户端对象
    var client={
        socket:socket,
        name:false
    }
    socket.on('login',function(name){
      
      client.name=name;
      if(!onlineUsers.hasOwnProperty(client.name)){
        onlineUsers[client.name]=client.name;
        onlineUserCount++; 
      }
      var obj={time:getTime()};
      obj['text']=`欢迎${client.name}加入`;
      obj['name']='系统';
      obj['type']='nome';
      obj['onlineUserCount']=onlineUserCount;
      //返回欢迎语
      socket.emit('system',obj);  //发送给自己的消息
      //广播新用户已登录
      socket.broadcast.emit('system',obj); //向其他用户发送消息
      console.log(onlineUsers)

    })
    socket.on('chat',function(msg){
      var obj={time:getTime()};
      var obj1={time:getTime()};
      obj['text']= msg;
      obj['name']= client.name;
      obj['type']='isme';
      obj['onlineUserCount']=onlineUserCount;
      obj1['text']= msg;
      obj1['name']= client.name;
      obj1['type']='nome';
      obj1['onlineUserCount']=onlineUserCount;
      socket.emit('system',obj);
      socket.broadcast.emit('system',obj1);
      console.log(onlineUsers)
      
    })
   
 
    socket.on('disconnect',function(){
        if(onlineUsers.hasOwnProperty(client.name)){
            onlineUserCount--;
            delete onlineUsers[client.name];
        }
        var obj={
            time:getTime(),
            name:'系统',
            text:client.name+'下线了',
            type:'nome',
            onlineUserCount:onlineUserCount,
        };
        //广播用户退出
        console.log(onlineUsers,client.name)
        socket.broadcast.emit('system',obj); //用户登录和退出都使用system事件播报
        console.log(client.name+' disconnect,当前在线人数:'+onlineUserCount);
    });
});


http.listen(3000, function () {
  console.log('port is 3000')
})


var getTime=function(){
  var date = new Date();
  return date.getHours()+":"+date.getMinutes()+":"+date.getSeconds();
}
 



